/**
 * @date 2021-01-14 14:48:01
 * @remark
 */

// lib
import {
  CameraOptions,
  ImageLibraryOptions,
  ImagePickerResponse,
  launchCamera,
  launchImageLibrary,
} from "react-native-image-picker";
import { Image as ImageCompressor } from "react-native-compressor";
// config
// script & methods & public
import toast from "cts/toast";
import permissions from "core/permissions";
// biz
// store
// service
// interface && type
// 其它

async function useImageLibrary(
  options: ImageLibraryOptions,
  ok: (uri: string, res: ImagePickerResponse) => void,
  isCompress = true,
) {
  const can = await permissions.checkWhenNeedPhoto(false);
  if (!can) return;
  launchImageLibrary(options, (res) => {
    if (res.errorCode && res.errorMessage) {
      toast.error(`${res.errorCode}: ${res.errorMessage}`);
      return;
    }
    if (!res.didCancel && res.assets) {
      const [assets] = res.assets;
      if (!assets || !assets.uri) {
        toast.error("没有获得文件路径");
        return;
      }
      if (isCompress && assets.fileSize && assets.fileSize > 3500000) {
        ImageCompressor.compress(assets.uri, {
          maxWidth: 5000,
          maxHeight: 5000,
          quality: 0.9,
        }).then((result) => {
          ok(result, res);
        });
      } else {
        ok(assets.uri, res);
      }
    }
  });
}

async function useCamera(
  options: CameraOptions,
  ok: (uri: string, res: ImagePickerResponse) => void,
  isCompress = true,
) {
  const can = await permissions.checkWhenNeedPhoto(true);
  if (!can) return;
  launchCamera(options, (res) => {
    if (res.errorCode && res.errorMessage) {
      toast.error(`${res.errorCode}: ${res.errorMessage}`);
      return;
    }
    if (!res.didCancel && res.assets) {
      const [assets] = res.assets;
      if (!assets || !assets.uri) {
        toast.error("没有获得文件路径");
        return;
      }
      if (isCompress && assets.fileSize && assets.fileSize > 3500000) {
        ImageCompressor.compress(assets.uri, {
          maxWidth: 5000,
          maxHeight: 5000,
          quality: 0.9,
        }).then((result) => {
          ok(result, res);
        });
      } else {
        ok(assets.uri, res);
      }
    }
  });
}

export default {
  useImageLibrary,
  useCamera,
};
